<template>
  <div class="question-detail-container">
    <!-- 问题卡片 -->
    <el-card class="question-card">
      <h1>{{ question.title }}</h1>
      <div class="question-meta">
        <span>{{ question.author?.name }}</span>
        <span>{{ formatTime(question.createdAt) }}</span>
        <el-tag>{{ question.category }}</el-tag>
      </div>
      <div class="question-content" v-html="question.content"></div>
      <div class="question-actions">
        <el-button type="primary" @click="showAnswerForm = true">回答问题</el-button>
      </div>
    </el-card>

    <!-- 回答弹窗 -->
    <el-dialog v-model="showAnswerForm" title="回答心理问题">
      <el-form ref="answerForm" :model="answerForm" label-width="80px">
        <el-form-item label="回答内容">
          <el-input
              type="textarea"
              v-model="answerForm.content"
              rows="5"
              placeholder="请分享你的观点或建议..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAnswerForm = false">取消</el-button>
        <el-button type="primary" @click="submitAnswer">提交回答</el-button>
      </template>
    </el-dialog>

    <!-- 回答列表 -->
    <div class="answers-header">
      <h2>{{ answers.length }} 个回答</h2>
    </div>
    <el-card
        v-for="answer in answers"
        :key="answer.id"
        class="answer-card"
    >
      <div class="answer-content" v-html="answer.content"></div>
      <div class="answer-meta">
        <span>{{ answer.author?.name }}</span>
        <span>{{ formatTime(answer.createdAt) }}</span>
        <el-button
            type="text"
            @click="toggleLike(answer.id, !answer.liked)"
            class="like-button"
        >
          <el-icon :color="answer.liked ? '#F56C6C' : '#909399'">
            <StarFilled v-if="answer.liked" />
            <Star v-else />
          </el-icon>
          <span :class="{ 'liked-text': answer.liked }">{{ answer.likesCount }} 点赞</span>
        </el-button>
        <el-button type="text" @click="openReply(answer.id)">回复</el-button>
      </div>

      <!-- 回复列表 -->
      <div class="replies" v-if="answer.replies && answer.replies.length > 0">
        <h3>回复</h3>
        <el-card
            v-for="reply in answer.replies"
            :key="reply.id"
            class="reply-card"
        >
          <div class="reply-content">{{ reply.content }}</div>
          <div class="reply-meta">
            <span>{{ reply.author?.name }}</span>
            <span>{{ formatTime(reply.createdAt) }}</span>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 回复弹窗 -->
    <el-dialog v-model="showReplyForm" title="回复回答">
      <el-form ref="replyForm" :model="replyForm" label-width="80px">
        <el-form-item label="回复内容">
          <el-input
              type="textarea"
              v-model="replyForm.content"
              rows="3"
              placeholder="请输入你的回复..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReplyForm = false">取消</el-button>
        <el-button type="primary" @click="submitReply">提交回复</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// 引入图标组件
import { Star, StarFilled } from '@element-plus/icons-vue'

const route = useRoute()
const questionId = route.params.id as string // 从路由获取问题ID
const question = ref<any>({})
const answers = ref<any[]>([])
const showAnswerForm = ref(false)
const showReplyForm = ref(false)
const answerForm = reactive({ content: '' })
const replyForm = reactive({ content: '', answerId: '' })

// 获取问题详情与回答列表
const fetchQuestionDetail = async () => {
  try {
    // 获取问题详情
    const questionRes = await axios.get(`/api/questions/${questionId}`)
    question.value = questionRes.data

    // 获取该问题的回答列表
    const answersRes = await axios.get(`/api/questions/${questionId}/answers`)
    answers.value = answersRes.data
  } catch (err) {
    ElMessage.error('获取问题详情失败')
    console.error(err)
  }
}

// 提交回答
const submitAnswer = async () => {
  try {
    await axios.post(`/api/questions/${questionId}/answers`, { content: answerForm.content })
    ElMessage.success('回答提交成功～')
    showAnswerForm.value = false
    answerForm.content = ''
    fetchQuestionDetail() // 刷新回答列表
  } catch (err) {
    ElMessage.error('回答提交失败，请重试')
    console.error(err)
  }
}

// 点赞/取消点赞
const toggleLike = async (answerId: number, liked: boolean) => {
  try {
    if (liked) {
      await axios.post(`/api/answers/${answerId}/like`)
    } else {
      await axios.delete(`/api/answers/${answerId}/like`)
    }
    ElMessage.success(liked ? '点赞成功～' : '取消点赞成功～')
    fetchQuestionDetail() // 刷新点赞状态
  } catch (err) {
    ElMessage.error(liked ? '点赞失败' : '取消点赞失败')
    console.error(err)
  }
}

// 打开回复弹窗（记录要回复的回答ID）
const openReply = (answerId: number) => {
  replyForm.answerId = answerId + ''
  showReplyForm.value = true
}

// 提交回复
const submitReply = async () => {
  try {
    await axios.post(`/api/answers/${replyForm.answerId}/replies`, { content: replyForm.content })
    ElMessage.success('回复提交成功～')
    showReplyForm.value = false
    replyForm.content = ''
    fetchQuestionDetail() // 刷新回复列表
  } catch (err) {
    ElMessage.error('回复提交失败，请重试')
    console.error(err)
  }
}

// 时间格式化
const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

onMounted(() => fetchQuestionDetail())
</script>

<style scoped>
.question-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.question-card {
  margin-bottom: 20px;
}
.question-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #666;
  margin: 10px 0;
}
.question-content {
  line-height: 1.8;
  margin: 15px 0;
}
.question-actions {
  margin-top: 15px;
}
.answers-header {
  margin: 20px 0;
}
.answer-card {
  margin-bottom: 15px;
}
.answer-content {
  line-height: 1.6;
  margin-bottom: 10px;
}
.answer-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #666;
  font-size: 14px;
}
.like-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0;
  border: none;
  background: transparent;
  cursor: pointer;
}
.liked-text {
  color: #F56C6C;
}
.replies {
  margin-top: 10px;
}
.reply-card {
  margin-top: 10px;
  padding: 10px;
}
.reply-content {
  margin-bottom: 5px;
}
.reply-meta {
  display: flex;
  gap: 10px;
  color: #999;
  font-size: 12px;
}
</style>